function EEG = preprocess(filename, samplingRate, lowP, highP,latency)
%PREPROCESS 对数据的前处理，包括读数据，降采样和带通滤波和epoch，需要先startupBCI2000()和EEGLAB
%---input---
%filename: 数据路径
%samplingRate: 降采样频率
%lowP：带通低频
%highP：带通高频
%latency： SSVEP延迟，单位ms
%---output---
%EEG：EEG结构体
[data, states, params, ~, ~] = load_bcidat(filename);
EEG = pop_importdata('data',data','srate',params.SamplingRate.NumericValue);
EEG.state = states;
EEG.params = params;
EEG = pop_resample(EEG, samplingRate);
if highP>50 && lowP<50
    EEG = pop_eegfiltnew(EEG,'locutoff',49,'hicutoff',51,'revfilt',1);
end
EEG = pop_eegfiltnew(EEG,'locutoff',lowP);
EEG = pop_eegfiltnew(EEG,'hicutoff',highP);  %最好分开算，不然两边的斜率会强行一样，低频会非常抖，可能会不稳定
tasktime = find(EEG.state.RestCode == 0);
tasktime = tasktime(find(tasktime >= 100));
starttime = tasktime(find(diff(tasktime,2) > 0) + 2);
EEG.starttime = [tasktime(1) starttime'];
EEG.starttime = EEG.starttime + latency/1000 * samplingRate;
endtime = tasktime(find(diff(tasktime,2) > 0) + 1);
EEG.endtime = [endtime' tasktime(end)];
if sum(EEG.state.TargetCode) == 0  % SSVEP，划为8个epoch
    EEG.condition = 'SSVEP';
    for trial = 1:8
        EEG.epoch{trial} = EEG.data(:,EEG.starttime(trial):EEG.endtime(trial));
    end
elseif sum(EEG.state.StimulusCode == 0)  % MI,划为20个epoch
    EEG.condition = 'MI';
    for trial = 1:20
        EEG.epoch{trial} = EEG.data(:,EEG.starttime(trial):EEG.endtime(trial));
    end
end
end

